<template>
  <div>
    <!-- 面包屑导向 -->
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCateDIialogVisible"
            >添加分类</el-button
          >
        </el-col>
      </el-row>

      <!-- 添加分类弹出的对话框 -->
      <el-dialog
        title="提示"
        :visible.sync="CateDIialogVisible"
        @close="addCateDialogClosed"
      >
        <el-form
          :model="addCateForm"
          :rules="addCateFromRuls"
          ref="addCateFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>

          <el-form-item label="父级分类">
            <el-cascader
              v-model="selectKeys"
              :options="parentList"
              :props="cateProps"
              @change="cateChange"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="CateDIialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加列表 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        border
        index-text="#"
        class="treeTable"
      >
        <!-- 是否有效 -->
        <template slot="isOk" slot-scope="scope">
          <i
            style="color: lightgreen"
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
          ></i>
          <i
            style="color: red"
            class="el-icon-error"
            v-if="scope.row.cat_deleted === true"
          ></i>
        </template>

        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" type="success" v-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-if="scope.row.cat_level === 2"
            >三级</el-tag
          >
        </template>

        <!-- 编辑 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="editCate(scope.row.cat_id)"
            >编辑
          </el-button>
          <!-- <span>{{scope.row.cat_id}} {{scope.row.cat_name}}</span> -->
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeCate(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 编辑弹出对话框 -->
      <el-dialog title="编辑" :visible.sync="editDialogVisible" @close="editClose">
        <el-form
          ref="editFormRef"
          :model="editCataForm"
          :rules="addCateFromRuls"
          label-width="80px"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="editCataForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editFinish">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 导航栏 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Cate',
  data() {
    return {
      queryInfo: {
        type: 3,
        //当前页码
        pagenum: 1,
        //每页显示多少条数据
        pagesize: 5,
      },
      //获取商品列表
      cateList: [],
      //保存选中的一级和耳机列表的数据
      selectKeys: [],
      //级联选择器的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true,
        expandTrigger: 'hover',
      },
      //页面总条数
      total: 0,
      parentList: [],
      //添加列表columns每行所展示的数据
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isOk',
        },
        {
          label: '排序',
          type: 'template',
          template: 'order',
        },
        {
          label: '编辑',
          type: 'template',
          template: 'opt',
        },
      ],
      CateDIialogVisible: false,
      editDialogVisible: false,
      //增加分类的表单数据
      addCateForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0,
      },
      //表单验证规则
      addCateFromRuls: {
        cat_name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
      },
      //修改分类信息
      editCataForm: {},
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        this.$message.error('获取商品列表失败')
      }
      this.cateList = res.data.result
      this.total = res.data.total
      console.log(res)
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    addCateDIialogVisible() {
      this.getParentList()
      this.CateDIialogVisible = true
    },
    //获取父级列表
    async getParentList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 },
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级列表失败')
      } else {
        this.parentList = res.data
        console.log(res.data)
      }
    },
    cateChange() {
      console.log(this.selectKeys)
      //如果selectKeys数组的长度大于0 说明增加的有父属性
      if (this.selectKeys.length > 0) {
        //this.addCateForm.cat_pid 他的父级id就是selectKeys数组的最后一项
        this.addCateForm.cat_pid = this.selectKeys[this.selectKeys.length - 1]
        //当前分类当前层级永远和数组的长度相同
        this.addCateForm.cat_level = this.selectKeys.length
        return
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    addCate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post(
          'categories',
          this.addCateForm
        )
        if (res.meta.status !== 201) {
          this.$message.error('添加分类失败')
        }
        this.$message.success('添加分类成功')
        this.getCateList()
        this.CateDIialogVisible = false
        console.log(this.addCateForm)
        // console.log(res);
      })
    },
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.selectKeys = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    },
    //编辑按钮
    async editCate(id) {
      //查询出需要编辑的id
      //根据id查询出名称并渲染到input框中
      //通过对应的api接口进行编辑功能的实现
      const { data: res } = await this.$http.get(`categories/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('修改失败')
      }
      this.editCataForm = res.data
      // console.log(this.editCataForm)
      this.editDialogVisible = true
    },
    //确定编辑
    editFinish() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.editCataForm.cat_id}`,
          {
            cat_name: this.editCataForm.cat_name,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.getCateList()
        this.$message.success('修改成功')
        this.editDialogVisible = false
      })
    },
    //删除功能的实现
    async removeCate(id) {
      const {data:res} = await this.$http.delete(`categories/${id}`)
      if(res.meta.status !== 200) {
        return this.$message.error('删除分类失败')
      }
      this.$message.success('删除分类成功')
      this.getCateList()
    },
      editClose() {
        this.$refs.editFormRef.resetFields()
      }
  },
  created() {
    this.getCateList()
  },
}
</script>

<style scoped>
.treeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>